package leetcode.code1648;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

import leetcode.IDebug;

public class Solution2 implements IDebug {

	int mod = (int) 1e9 + 7;

	public int maxProfit(int[] inventory, int orders) {
		long ans = 0;
		Map<Integer, Integer> map = new HashMap<>();// 个数，几种
		for (int cur : inventory) {
			map.put(cur, map.getOrDefault(cur, 0) + 1);
		}
		PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
			pq.add(new int[] { entry.getKey(), entry.getValue() });
		}
		while (orders > 0) {
			int[] cur = pq.poll();
			int value = cur[0], size = cur[1];
			if (size <= orders) {
				ans += value * size;
				orders -= size;
				if (!pq.isEmpty() && pq.peek()[0] == value - 1) {
					int[] next = pq.poll();
					pq.add(new int[] { value - 1, size + next[1] });
				} else {
					pq.add(new int[] { value - 1, size });
				}
			} else {
				ans += orders * value;
				orders = 0;
			}
			ans %= mod;
		}
		return (int) ans;
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
